package jinyilw.swing.visuals.panel;

import jinyilw.swing.Alignment;

import java.awt.Component;
import java.awt.Container;

public class FlowPanel extends Container // 自定义流式面板
{
	private static final long serialVersionUID = -1755251296027608454L;
	private Alignment align = Alignment.RIGHT;
	private int currentW = 0;
	private int currentH = 0;

	public FlowPanel()
	{
	}

	public FlowPanel(Alignment align)
	{
		this.align = align;
	}

	public void setAlignment(Alignment align)
	{
		this.align = align;
		updateComps();
	}

	@Override
	protected void addImpl(Component comp, Object constraints, int index)
	{
		super.addImpl(comp, constraints, index);
		updateComps();
	}

	@Override
	public void remove(int index)
	{
		Component[] comps = getComponents();
		if (index < 0 || index >= comps.length)
			return;
		super.remove(index);
		updateComps();
	}

	public void updateComps()
	{
		Component[] comps = getComponents();
		if (comps == null)
			return;
		int x = 0, y, h;
		currentW = 0;
		for (Component c : comps)
		{
			currentW += c.getWidth();
			h = c.getHeight();
			if (h > currentH)
				currentH = h;
		}
		setSize(currentW, currentH);
		if (align == Alignment.RIGHT)
			for (int i = comps.length - 1; i >= 0; i--)
			{
				y = (currentH - comps[i].getHeight()) / 2;
				comps[i].setLocation(x, y);
				x += comps[i].getWidth();
			}
		else if (align == Alignment.LEFT)
			for (Component comp : comps)
			{
				y = (currentH - comp.getHeight()) / 2;
				comp.setLocation(x, y);
				x += comp.getWidth();
			}
	}
}
